package com.wangyi.fightimg.utils.http.download;

import android.content.Context;

import com.wangyi.fightimg.R;
import com.wangyi.fightimg.utils.ConstantUtil;
import com.wangyi.fightimg.widget.CustomDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author wangYi
 *  下载图片
 */

public class DownloadImg {
    private static OkHttpClient okHttpClient;
    private static DownloadImg downloadImg;
    private CustomDialog customDialog;
    private static Context mContext;

    public DownloadImg() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(100000, TimeUnit.MICROSECONDS)
                .readTimeout(100000, TimeUnit.MICROSECONDS)
                .writeTimeout(100000, TimeUnit.MICROSECONDS)
                .build();
    }

    public static DownloadImg getInstance(Context context) {
        mContext = context;
        if (downloadImg == null) {
            synchronized (DownloadImg.class) {
                if (downloadImg == null) {
                    downloadImg = new DownloadImg();
                }
            }
        }
        return downloadImg;
    }

    /**
     * @param url
     */
    public void startDownload(String url, final DownloadListener listener) {
        showDialog();
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response response = chain.proceed(chain.request());
                DownloadResponseBody downloadResponseBody = new DownloadResponseBody(response.body(), listener);
                return response.newBuilder().body(downloadResponseBody).build();
            }
        };
        okHttpClient.newBuilder().addNetworkInterceptor(interceptor);
        final String basePath = ConstantUtil.imgUriBas;
        final String fileName = basePath + "/" + url.split("/")[url.split("/").length - 1];
        final Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onFaile(e.toString());
                dismissDialog();
                listener.onFaile(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (request != null) {
                    InputStream inputStream = response.body().byteStream();
                    FileOutputStream fileOutputStream = new FileOutputStream(new File(fileName));
                    int lenght = 0;
                    byte[] buffer = new byte[1024];
                    while (-1 != (lenght = inputStream.read(buffer))) {
                        fileOutputStream.write(buffer, 0, lenght);
                    }
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    inputStream.close();
                    listener.onSuccess();
                }
                dismissDialog();
            }
        });
    }

    /**
     * 展示对话框
     */
    private void showDialog() {
        if (customDialog == null) {
            customDialog = new CustomDialog(mContext);
            customDialog.createDialog(R.layout.dialog_progress);
        }
        customDialog.show();
    }

    private void dismissDialog() {
        if (customDialog != null) {
            customDialog.dismiss();
        }
    }
}
